//
//  MemberDetailVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/7.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import Eureka
import SCLAlertView
import SVProgressHUD


class MemberDetailVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    let refreshControl = UIRefreshControl()
    let storeHelper = StoreVCHelper()
    var Members = [Member]()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UINib(nibName: "MemberDetailCell", bundle: nil), forCellReuseIdentifier: "MemberDetailCell")
        tableView.insertSubview(refreshControl, at: 0)
        
        refreshControl.addTarget(self, action: #selector(refresh(_:)), for: .valueChanged)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        reloadData()
    }
    func reloadData() {
        storeHelper.getAllMembers { (success, members) in
            if success {
                self.Members = members!
                self.tableView.reloadData()
            } else {
                self.showError(message: "网络错误，请重试!")
            }
            self.refreshControl.endRefreshing()
        }
    }
    
    @IBAction func addMemberTapped(_ button: UIButton!) {
        let apperance = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: false)
        let alert = SCLAlertView(appearance: apperance)
        let phoneTextField = alert.addTextField("手机号")
        phoneTextField.keyboardType = .phonePad
        let nameTextField = alert.addTextField("备注信息/姓名")
        alert.addButton("添加成员") {
            guard phoneTextField.text != "", nameTextField.text != "" else {
                return
            }
            SVProgressHUD.show()
            self.storeHelper.addMember(phone: phoneTextField.text!, authority: 1, memberName: nameTextField.text!, completeHandler: { (success, errorMessage) in
                if success {
                    SVProgressHUD.showSuccess(withStatus: "成功添加")
                    self.tableView.reloadData()
                } else {
                    SVProgressHUD.showError(withStatus: errorMessage ?? "网络错误")
                }
                SVProgressHUD.dismiss(withDelay: 2.0)
                alert.hideView()
            })
        }
        alert.showEdit("添加成员", subTitle: "输入手机号以添加成员，注意已被添加到商店的用户不能重复添加")
    }
    

    @objc
    func refresh(_ refreshView: UIRefreshControl) {
        reloadData()
        refreshView.endRefreshing()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Members.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MemberDetailCell") as! MemberDetailCell
        if Members[indexPath.row].authority == 0 {
            cell.phoneLabel.text = Members[indexPath.row].memberId + "（管理员）"
        } else {
            cell.phoneLabel.text = Members[indexPath.row].memberId + "（成员）"
        }
        cell.phoneLabel.text = Members[indexPath.row].memberId
        cell.nameLabel.text = Members[indexPath.row].name
        cell.selectionStyle = .none
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let memberEditVC = MemberEditVC()
        memberEditVC.member = Members[indexPath.row]
        navigationController?.pushViewController(memberEditVC, animated: true)
    }
    

}

